<template>
  <!-- 音乐播放器主容器 -->
  <div class="music-player h-screen flex flex-col overflow-hidden" :style="{ backgroundColor: backgroundColor }">
    <div class="flex-1 flex">
      <!-- 左侧歌词区域 -->
      <div class="w-1/3  p-4 overflow-hidden">
        <h2 class="text-xl font-bold mb-4 text-center">歌词</h2>
        <div class="lyrics-container text-center relative container-z" ref="lyricsContainer">
          <div  class=" lyrics-scroll-container overflow-hidden transition-transform" ref="lyricsScrollContainer">
            <div v-for="(item, index) in lyrics" :key="index" :class="{ 'current-lyric': index === currentLyricIndex }" class="lyric-item py-2 text-gray-400">
              {{ item.lyric }}
            </div>
          </div>
          <div v-if="lyrics.length === 0" class="text-gray-400 absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2">
            上传音乐和歌词文件开始播放
          </div>
        </div>
      </div>

      <!-- 右侧频谱区域 -->
      <div class="w-2/3  p-4 flex flex-col">
        <div class="flex justify-between items-center mb-4">
        <h2 class="text-xl font-bold">音频频谱</h2>
        <div class="flex items-center space-x-2">
          <span class="text-sm">背景颜色:</span>
          <input type="color" v-model="backgroundColor" class="w-8 h-8 p-0 border-0 rounded-full cursor-pointer" title="选择背景颜色">
        </div>
          <div class="w-40">
            <select v-model="spectrumType" class="w-full bg-dark border border-gray-400 rounded px-3 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
              <option value="bar">柱状</option>
              <option value="altBar">细柱</option>
              <option value="circle">圆形</option>
              <option value="grayscale">灰黑色</option>
              <option value="wave">波浪形</option>
              <option value="gradient">渐变色彩</option>
              <option value="pulse">脉冲效果</option>
            </select>
          </div>
        </div>
        <div class="flex-1 flex items-end justify-center">
          <AudioSpectrum :spectrum-type="spectrumType" :audio-context="audioContext" :analyser-node="analyserNode" />
        </div>
      </div>
    </div>

    <!-- 底部控制区域 -->
    <div class="bg-dark p-4 border-t border-gray-dark">
      <div v-if="currentSong" class="mb-2 flex justify-between items-center">
        <div class="text-left">
          <div class="font-bold">{{ currentSong.name }}</div>
          <div class="text-sm text-gray-400">{{ currentSong.artist || '未知艺术家' }}</div>
        </div>
        <div class="flex items-center space-x-4">
          <button class="text-gray-300 hover:text-white">
            <i class="fas fa-step-backward"></i>
          </button>
          <button class="text-gray-300 hover:text-white" @click="togglePlay">
            <i :class="isPlaying ? 'fas fa-pause' : 'fas fa-play'"></i>
          </button>
          <button class="text-gray-300 hover:text-white">
            <i class="fas fa-step-forward"></i>
          </button>
        </div>
      </div>

      <!-- 进度条 -->
      <div class="progress-bar mt-2" @click="seek">
        <div class="progress-fill" :style="{ width: progress + '%' }"></div>
      </div>
      <div class="flex justify-between text-xs text-gray-400 mt-1">
        <div>{{ formatTime(currentTime) }}</div>
        <div>{{ formatTime(duration) }}</div>
      </div>

      <!-- 文件上传 -->
      <div class="mt-4 grid grid-cols-1 md:grid-cols-2 gap-4">
        <label for="file-upload" class="flex items-center justify-center w-full">
          <div class="flex flex-col items-center justify-center w-full h-12 border-2 border-dashed border-gray-400 rounded-lg cursor-pointer bg-dark hover:bg-gray-dark transition-colors">
            <div class="flex flex-col items-center justify-center pt-10 pb-6">
              <p class="mb-2 text-sm text-gray-400">    <i class="fas fa-music text-gray-400 mb-2"></i><span class="font-semibold">点击上传</span> 或拖放音乐文件 支持 MP3, WAV 格式</p>
            </div>
            <input id="file-upload" type="file" class="hidden" accept=".mp3,.wav" @change="handleFileUpload" />
          </div>
        </label>
        <label for="lyrics-upload" class="flex items-center justify-center w-full">
          <div class="flex flex-col items-center justify-center w-full h-12 border-2 border-dashed border-gray-400 rounded-lg cursor-pointer bg-dark hover:bg-gray-dark transition-colors">
            <div class="flex flex-col items-center justify-center pt-10 pb-6">
             
              <p class="mb-2 text-sm text-gray-400"> <i class="fas fa-file-alt text-gray-400 mb-2"></i><span class="font-semibold">点击上传</span> 或拖放歌词文件 支持 LRC 格式</p>
            </div>
            <input id="lyrics-upload" type="file" class="hidden" accept=".lrc" @change="handleLyricsUpload" />
          </div>
        </label>
      </div>
    </div>
  </div>
</template>

<script>
import AudioSpectrum from './AudioSpectrum'

export default {
  name: 'MusicPlayer',
  components: {
    AudioSpectrum
  },
  data() {
    return {
      backgroundColor: '#1a1a1a', // 默认背景色
      audio: null, // 音频对象
      audioContext: null, // 音频上下文
      analyserNode: null, // 分析器节点
      isPlaying: false, // 是否正在播放
      currentTime: 0, // 当前播放时间
      duration: 0, // 音频总时长
      progress: 0, // 播放进度
      currentSong: null, // 当前歌曲信息
      spectrumType: 'bar', // 频谱类型
      lyrics: [], // 歌词数组
      currentLyricIndex: -1 // 当前歌词索引
    }
  },
  methods: {
    handleFileUpload(e) {
      const file = e.target.files[0]
      if (!file) return

      // 重置音频
      if (this.audio) {
        this.audio.pause()
        this.audio = null
      }

      // 创建新的音频对象
      this.audio = new Audio(URL.createObjectURL(file))
      this.currentSong = {
        name: file.name.replace(/\.(mp3|wav)$/, ''),
        artist: '未知艺术家'
      }

      // 初始化音频上下文和分析器节点
      this.initAudioContext()

      // 绑定事件
      this.audio.addEventListener('timeupdate', this.updateProgress)
      this.audio.addEventListener('ended', this.handleEnded)

      // 不自动播放，等待用户点击播放按钮
      this.isPlaying = false
    },

    // 处理歌词文件上传
    handleLyricsUpload(e) {
      const file = e.target.files[0]
    
      if (!file) return

      // 重置歌词
      this.lyrics = []
      this.currentLyric = null
      this.currentLyricIndex = -1

      // 读取歌词文件
      const reader = new FileReader()
      reader.onload = (event) => {
        const content = event.target.result
        this.parseLyrics(content)
      }
      reader.readAsText(file, 'utf-8')
    },

    // 解析LRC歌词
    parseLyrics(content) {
      console.log('歌词内容:', content);
      const lines = content.split('\n')
      const timeRegex = /\[(\d+):(\d+\.\d+)\]/

      lines.forEach(line => {
        const match = line.match(timeRegex)
        if (match) {
          const minutes = parseInt(match[1])
          const seconds = parseFloat(match[2])
          const time = minutes * 60 + seconds
          const lyric = line.replace(timeRegex, '').trim()

          if (lyric) {
            this.lyrics.push({
              time,
              lyric
            })
            console.log('解析到歌词:', { time, lyric });
          }
        }
      })

      // 按时间排序
      this.lyrics.sort((a, b) => a.time - b.time)
      console.log('解析完成的歌词数组:', this.lyrics);
    },

    initAudioContext() {
      if (!this.audioContext) {
        this.audioContext = new (window.AudioContext || window.webkitAudioContext)()
      }

      // 创建分析器节点
      this.analyserNode = this.audioContext.createAnalyser()
      this.analyserNode.fftSize = 256

      // 创建音频源
      const source = this.audioContext.createMediaElementSource(this.audio)
      source.connect(this.analyserNode)
      this.analyserNode.connect(this.audioContext.destination)
    },

    play() {
      if (!this.audio) return

      // 确保音频上下文已启动
      if (this.audioContext && this.audioContext.state === 'suspended') {
        this.audioContext.resume()
      }

      this.audio.play()
      this.isPlaying = true
    },

    pause() {
      if (!this.audio) return

      this.audio.pause()
      this.isPlaying = false
    },

    togglePlay() {
      if (this.isPlaying) {
        this.pause()
      } else {
        this.play()
      }
    },

    updateProgress() {
      if (!this.audio) return

      this.currentTime = this.audio.currentTime
      this.duration = this.audio.duration
      this.progress = (this.currentTime / this.duration) * 100

      // 歌词同步逻辑
      if (this.lyrics.length > 0) {
        console.log('当前时间:', this.currentTime, '歌词数量:', this.lyrics.length);
        // 找到当前应该显示的歌词
        let newIndex = -1
        for (let i = 0; i < this.lyrics.length; i++) {
          if (this.lyrics[i].time <= this.currentTime) {
            newIndex = i
          } else {
            break
          }
        }

        if (newIndex !== this.currentLyricIndex) {
          console.log('更新歌词索引:', newIndex);
          this.currentLyricIndex = newIndex
          this.scrollToCurrentLyric()
        }
      }
    },

    // 滚动到当前歌词
    scrollToCurrentLyric() {
      if (this.currentLyricIndex === -1 || !this.$refs.lyricsScrollContainer || !this.$refs.lyricsContainer) {
        console.log('无法滚动到当前歌词: 缺少引用或索引为-1');
        return
      }

      const scrollContainer = this.$refs.lyricsScrollContainer
      const lyricItems = scrollContainer.querySelectorAll('.lyric-item')
      if (!lyricItems || lyricItems.length === 0) {
        console.log('没有找到歌词项');
        return
      }

      const currentLyric = lyricItems[this.currentLyricIndex]
      const container = this.$refs.lyricsContainer

      // 计算滚动位置
      const containerHeight = container.clientHeight
      const lyricHeight = currentLyric.clientHeight
      const lyricTop = currentLyric.offsetTop

      // 使当前歌词居中
      const scrollPosition = lyricTop - (containerHeight / 2) + (lyricHeight / 2)
      console.log('滚动位置:', scrollPosition);

      // 应用滚动
      scrollContainer.style.transform = `translateY(-${scrollPosition}px)`
    },

    handleEnded() {
      this.isPlaying = false
      this.currentTime = 0
      this.progress = 0
    },

    seek(e) {
      if (!this.audio) return

      const progressBar = e.currentTarget
      const clickPosition = e.offsetX
      const progress = (clickPosition / progressBar.offsetWidth) * 100

      this.currentTime = (progress / 100) * this.duration
      this.audio.currentTime = this.currentTime
      this.progress = progress
    },

    formatTime(seconds) {
      if (!seconds || isNaN(seconds)) return '00:00'

      const minutes = Math.floor(seconds / 60)
      const remainingSeconds = Math.floor(seconds % 60)

      return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
    }
  },
  beforeDestroy() {
    if (this.audio) {
      this.audio.pause()
      this.audio = null
    }

    if (this.audioContext) {
      this.audioContext.close()
      this.audioContext = null
    }
  }
}
</script>

<style scoped>
/* 歌词容器样式 */
.lyrics-container {
  position: relative;
  overflow: hidden;
}

/* 歌词滚动容器样式 */
.lyrics-scroll-container {
  width: 100%;
  will-change: transform;
}

/* 歌词项样式 */
.lyric-item {
  transition: all 0.3s ease;
  padding: 8px 0;
  color: white !important; /* 强制白色 */
  text-shadow: 1px 1px 0 black, /* 右下方向 */
                 -1px 1px 0 black, /* 左下方向 */
                 1px -1px 0 black, /* 右上方向 */
                 -1px -1px 0 black; /* 左上方向 */
                 paint-order: stroke;
  z-index: 10; /* 确保歌词在最上层 */
}

/* 当前歌词样式 */
.current-lyric {
  color: #FEDF15 !important; /* 蓝色 */
  font-size: 1.25rem;
  font-weight: bold;
  transform: scale(1.05);
}

/* 进度条样式 */
.progress-bar {
  height: 4px;
  background-color: #333;
  cursor: pointer;
  position: relative;
}

.progress-fill {
  height: 100%;
  background-color: #3b82f6;
  position: absolute;
  top: 0;
  left: 0;
}
.container-z{
  height: 700px;
  /* transform: rotateY(0deg) translateZ(50px); */
  /* 确保元素在3D空间中 */
  /* transform-style: preserve-3d; */
  /* 如果你想要看到透视效果，可以添加透视 */
}
</style>